package xx.services;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xx.db.QueryRunner;
import xx.entity.page.PageLayout;
import xx.services.util.Names;

public class Page
{
    private final ServletRequest request;

    private final ServletResponse response;

    private int pageHash;

    private PrintWriter out;

    private String title = null;

    private StringBuilder content = null;

    private String pattern = null;

    /** 缓存时间，单位（秒），默认为3小时(60 * 60 * 3) */
    private long cacheTime = 60 * 60 * 3;

    public Page(ServletRequest request, ServletResponse response)
    {
        this.request = request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Cache-Control", "public,max-age=" + cacheTime);
        res.setDateHeader("Expires", (new Date()).getTime() + 1000 * cacheTime);
        res.setHeader("content-type", "text/html; charset=UTF-8");

        this.response = res;

        init();

        content = new StringBuilder();
        // TODO Auto-generated constructor stub
    }

    @SuppressWarnings("unchecked")
    private void init()
    {
        try
        {
            out = response.getWriter();
            HttpServletRequest req = (HttpServletRequest) request;
            String uriPattern = req.getServletPath();
            if (req.getPathInfo() != null)
                uriPattern = uriPattern + req.getPathInfo();

            pattern = uriPattern.substring(1, uriPattern.indexOf("."));
//            StringBuilder sb = new StringBuilder(uriPattern + "?");
//            Enumeration<String> names = req.getParameterNames();
//            while (names.hasMoreElements())
//            {
//                String name = names.nextElement();
//                sb.append(name).append("=").append(req.getParameter(name)).append("&");
//            }

            pageHash = pattern.hashCode();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void go()
    {
        try
        {
            PageCache pc = PageCache.getInstance();

//            if (pc.contains(pageHash))
//            {
//                PageCache.Page page = pc.get(pageHash);
//                out.print(page != null ? page.getContent() : "你访问的页面不存在，或被删除！");
//                return;
//            }

            if (pattern.matches("index|default"))
            {
                goIndex();
            }
            else if (pattern.substring(0, 1).matches("\\d"))
            {
                goNum(Long.parseLong(pattern));
            }
            else
            {
                goP(pattern);
            }

            PageCache.Page page = pc.instancePage(pageHash, title, content.toString());

            pc.push(page, cacheTime);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private xx.entity.page.Page goIndex() throws SQLException
    {
        QueryRunner qr = new QueryRunner(Names.FRAMEWORK, null);
        xx.entity.page.Page page = new xx.entity.page.Page(qr, null);
        page.instanceIndex();
        writePage(page);
        return page;
    }

    private xx.entity.page.Page goNum(long pageId) throws SQLException
    {
        QueryRunner qr = new QueryRunner(Names.FRAMEWORK, null);
        xx.entity.page.Page page = new xx.entity.page.Page(qr, null);
        page.setPageId(pageId).load();
        writePage(page);
        return page;
    }

    private void writePage(xx.entity.page.Page page) throws SQLException
    {
        title = page.getTitle();
        String[] templet = page.getTemplet().split("\\$\\{container}");// .replaceAll("\\\r|\\\n|\\\t",
        // "")
        String header = templet[0].replaceAll("\\$\\{title}", page.getTitle()).replaceAll(
                "\\$\\{keywords}", page.getKeywords()).replaceAll("\\$\\{description}",
                page.getDescription());
        out.print(header);// .replaceAll("\\\r|\\\n|\\\t", "")
        out.print("\n");
        content.append(header);
        List<PageLayout> layouts = page.getLayouts();
        for (PageLayout layout : layouts)
        {
            // out.print(layout.toHtml());
            String html = layout.toHtml();// .replaceAll("\\\r|\\\n|\\\t", "");
            out.print(html);// .replaceAll("\\\r|\\\n|\\\t", "")
            out.print("\n");
            out.flush();
            content.append(html);
            // try
            // {
            // new Thread().sleep(3000);
            // }
            // catch (InterruptedException e)
            // {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
        }

        String footer = templet[1];
        out.print(footer);
        content.append(footer);
    }

    private xx.entity.page.Page goP(String pagekey) throws SQLException
    {
        QueryRunner qr = new QueryRunner(Names.FRAMEWORK, null);
        xx.entity.page.Page page = new xx.entity.page.Page(qr, null);
        page.setPagekey(pagekey).load();
        writePage(page);
        return page;
    }
}
